package com.base.system.base.http.origin;

import cn.hutool.json.JSONObject;
import com.base.system.base.http.HttpResult;
import com.base.system.enums.HttpStatus;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class AccessAllowOrigin {
    private HttpServletRequest req;
    private HttpServletResponse rep;

    public AccessAllowOrigin(HttpServletRequest req, HttpServletResponse rep) {
        this.req = req;
        this.rep = rep;
    }

    public void allowOrigin() {
        // 这里填写你允许进行跨域的主机ip（正式上线时可以动态配置具体允许的域名和IP）
        rep.setHeader("Access-Control-Allow-Origin", "*");
        // 允许的访问方法
        rep.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE, PATCH");
        // Access-Control-Max-Age 用于 CORS 相关配置的缓存
        rep.setHeader("Access-Control-Max-Age", "3600");
        rep.setHeader("Access-Control-Allow-Headers", "token,Origin, X-Requested-With, Content-Type, Accept");
        rep.setCharacterEncoding("UTF-8");
        rep.setContentType("application/json; charset=utf-8");
    }

    public void write(HttpStatus status, String msg) throws IOException {
        ServletOutputStream out = rep.getOutputStream();
        HttpResult faild = HttpResult.faild(status, msg);
        JSONObject jsonObject = new JSONObject(faild);
        byte[] bytes = (jsonObject.toStringPretty()).getBytes();
        out.write(bytes);
        out.flush();
        out.close();
        if (out.equals(null)) rep.flushBuffer();
    }

    public void write(HttpStatus status) throws IOException {
        write(status, null);
    }

    public void setStatus(HttpStatus status) {
        rep.setStatus(status.getCode());
    }
}
